package cn.bingo.yunsj.mail;

import cn.bingo.yunsj.common.exception.EmException;
import cn.bingo.yunsj.common.exception.OwnException;
import cn.bingo.yunsj.mail.model.FileProperties;
import cn.bingo.yunsj.mail.model.MailModel;
import cn.bingo.yunsj.mail.model.NewMailModel;
import cn.bingo.yunsj.utils.IsDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;

/**
 * 这个类处理邮件发送参数
 */
public class MailParam implements AbstractMail {

    private static final Logger logger = LoggerFactory.getLogger(MailParam.class);

    @Override
    public void sendSimpleMailMessage(MailModel mailModel) {

        if (mailModel == null) {
            throw new OwnException(EmException.PARAM_EXCPTION);
        }

        // 先进行参数处理，例如根据名称找word路径
        this.doMailParam(mailModel);
    }

    private void doMailParam(MailModel mailModel) {
        NewMailModel newMailModel = new NewMailModel();

        BeanUtils.copyProperties(mailModel, newMailModel);

        // 根据名称拼接模板路径
        String wordPath = FileProperties.getDocPath() + mailModel.getName();

        logger.info("模板路径：" + wordPath);

        //保留名称前缀
        String wordStart = mailModel.getName().substring(0, mailModel.getName().indexOf("."));

        logger.info("模板前缀：" + wordStart);

        //拼接html路径
        String htmlPath = FileProperties.getDocPath() + "html/" + wordStart + ".html";

        logger.info("html路径：" + htmlPath);

        newMailModel.setWordPath(wordPath);

        newMailModel.setHtmlPath(htmlPath);

        WordToHtml wordToHtml = new WordToHtml();

        try {
            wordToHtml.doWordToHtml(newMailModel);
        } catch (TransformerException e) {
            throw new OwnException(EmException.FILE_EXCPTION, e.getMessage());
        } catch (IOException e) {
            throw new OwnException(EmException.FILE_EXCPTION, e.getMessage());
        } catch (ParserConfigurationException e) {
            throw new OwnException(EmException.FILE_EXCPTION, e.getMessage());
        }
    }
}
